package com.nfu.zlsp.dev.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nfu.zlsp.dev.common.utils.OrderIdUtil;
import com.nfu.zlsp.dev.common.utils.PageUtils;
import com.nfu.zlsp.dev.common.utils.Query;
import com.nfu.zlsp.dev.common.utils.R;
import com.nfu.zlsp.dev.dao.AddressDao;
import com.nfu.zlsp.dev.dao.COrderDao;
import com.nfu.zlsp.dev.dao.ConsignDao;
import com.nfu.zlsp.dev.dao.UserDao;
import com.nfu.zlsp.dev.entity.*;
import com.nfu.zlsp.dev.entity.vo.OrderManagementConsignVo;
import com.nfu.zlsp.dev.entity.vo.OrderManagementTransportVo;
import com.nfu.zlsp.dev.entity.vo.QueryTransportVo;
import com.nfu.zlsp.dev.service.AddressService;
import com.nfu.zlsp.dev.service.COrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("cOrderService")
public class COrderServiceImpl extends ServiceImpl<COrderDao, COrderEntity> implements COrderService {


    @Autowired
    private ConsignDao consignDao;


    @Autowired
    private UserDao userDao;

    @Autowired
    private AddressService addressService;

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private COrderDao cOrderDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<COrderEntity> page = this.page(
                new Query<COrderEntity>().getPage(params),
                new QueryWrapper<COrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryOrderManagementConsignPage(Map<String, Object> params) {



        String creationTime = (String) params.get("creationTime");
        String unloadCity = (String) params.get("unloadCity");
        String logisticsType = (String) params.get("logisticsType");

        QueryWrapper<ConsignEntity> queryWrapper = new QueryWrapper<ConsignEntity>();

        queryWrapper.orderByDesc("creation_time");

        //unloadCity == null 表示要查询全部数据
        if (unloadCity == null){
            queryWrapper.eq("c_userid", params.get("c_userid")).eq("state", "1");
        }else{
            queryWrapper.eq("c_userid", params.get("c_userid")).eq("state", "1")
                    .eq("logistics_type",logisticsType);
        }

        //查询consign
        List<ConsignEntity> consignEntityList =  consignDao.selectList(queryWrapper);

        List<OrderManagementConsignVo> orderManagementConsignVoList = consignEntityList.stream().map(consignEntity -> {
            QueryWrapper<COrderEntity> q = new QueryWrapper<COrderEntity>();
            if(unloadCity == null){
                q.eq("c_id", consignEntity.getId());
            }else{
                q.eq("c_id", consignEntity.getId()).gt("creation_time",creationTime);
            }

            COrderEntity cOrderEntity = this.baseMapper.selectOne(q);

            OrderManagementConsignVo orderManagementConsignVo = new OrderManagementConsignVo();
            if (cOrderEntity != null) {
                //拷贝consignEntity到vo
                BeanUtils.copyProperties(consignEntity, orderManagementConsignVo);
                //拷贝 cOrderEntity到vo
                orderManagementConsignVo.setCId(cOrderEntity.getCId());
                orderManagementConsignVo.setCreationTime(cOrderEntity.getCreationTime());
                orderManagementConsignVo.setTUserid(cOrderEntity.getTUserid());
                orderManagementConsignVo.setLogisticsInfo(cOrderEntity.getLogisticsInfo());
                orderManagementConsignVo.setLogisticsState(cOrderEntity.getLogisticsState());
                orderManagementConsignVo.setOrderState(cOrderEntity.getOrderState());
                orderManagementConsignVo.setContractState(cOrderEntity.getContractState());
                //查询承运方公司
                UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("id", cOrderEntity.getTUserid()));
                orderManagementConsignVo.setCompany(userEntity.getCompany() + "(" + userEntity.getNumber() + ")");
                //订单编号
                orderManagementConsignVo.setOrderId(cOrderEntity.getId());

                //根据地区编号查赋予细地址
                String pickAddress = addressService.getAddressByRegionId(consignEntity.getPickupAddress());
                String unloadAddress = addressService.getAddressByRegionId(consignEntity.getUnloadAddress());
                pickAddress += consignEntity.getPickupDetailAddress();
                unloadAddress += consignEntity.getUnloadDetailAddress();
                orderManagementConsignVo.setPickupDetailAddress(pickAddress);
                orderManagementConsignVo.setUnloadDetailAddress(unloadAddress);


                /**
                 * 删选出地址不符合查询条件的
                 *  返回空的QueryTransportVo
                 */

                if (unloadCity != null){
                    AddressEntity endCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", consignEntity.getUnloadAddress()));
                    if(!endCity.getAddressRegionid().equals(unloadCity)){
                        //地址条件不符
                        return new OrderManagementConsignVo();
                    }
                }
                return orderManagementConsignVo;


            }else {
                return new OrderManagementConsignVo();
            }

        }).collect(Collectors.toList());

        //用迭代器删除值为空的元素（迭代器遍历不会报错 foreach会）
        Iterator iterator = orderManagementConsignVoList.iterator();
        while (iterator.hasNext()){
            OrderManagementConsignVo vo = (OrderManagementConsignVo) iterator.next();
            if(vo.getId() == null){
                iterator.remove();
            }

        }


        IPage<COrderEntity> page = this.page(
                new Query<COrderEntity>().getPage(params),
                new QueryWrapper<COrderEntity>()
        );
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(orderManagementConsignVoList);
        System.out.println("hhhhhhhhhhhhhhhhhhhhh:" + pageUtils.getList());
        return pageUtils;
    }

    @Override
    @Transactional
    public R savePayList(Map<String, Object> params) {
        COrderEntity cOrder = new COrderEntity();
        cOrder.setId(OrderIdUtil.getOrderId());
        cOrder.setCId((String) params.get("cId"));
        cOrder.setTUserid((String) params.get("t_userid"));
        cOrder.setCreationTime(new Date());
        cOrder.setLogisticsState(1);
        cOrder.setOrderState(0);
        cOrder.setContractState(1);
        int insert = this.baseMapper.insert(cOrder);
        if (insert >= 1){
            int result = consignDao.updateStateById(cOrder.getCId());
            if (result >= 1){
                return R.ok();
            }
        }
        return R.ok().put("data","拼单失败");

    }

    @Override
    public PageUtils queryMyOrderTransport(Map<String, Object> params) {

        String creationTime = (String) params.get("creationTime");
        String unloadCity = (String) params.get("unloadCity");
        String logisticsType = (String) params.get("logisticsType");

        QueryWrapper<COrderEntity> queryWrapper = new QueryWrapper<COrderEntity>();
        queryWrapper.orderByDesc("creation_time");

        if (unloadCity == null) {
            queryWrapper.eq("t_userid", params.get("t_userid"));
        }else{
            queryWrapper.eq("t_userid", params.get("t_userid")).gt("creation_time",creationTime);
        }

        List<COrderEntity> cOrderEntityList = cOrderDao.selectList(queryWrapper);

        List<OrderManagementConsignVo> orderManagementConsignVoList = cOrderEntityList.stream().map(cOrderEntity -> {
            QueryWrapper<ConsignEntity> q = new QueryWrapper<ConsignEntity>();

            OrderManagementConsignVo orderManagementConsignVo = new OrderManagementConsignVo();

            if (unloadCity == null){
                q.eq("id", cOrderEntity.getCId());
            }else{
                q.eq("id", cOrderEntity.getCId()).eq("logistics_type",logisticsType);
            }

            ConsignEntity consignEntity = consignDao.selectOne(q);

            if (consignEntity != null) {
                //查询公司并写入
                UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("id", consignEntity.getCUserid()));
                orderManagementConsignVo.setCompany(userEntity.getCompany() + "(" + userEntity.getNumber() + ")");

                //copy consignEntity
                BeanUtils.copyProperties(consignEntity, orderManagementConsignVo);
                orderManagementConsignVo.setOrderId(cOrderEntity.getId());
                orderManagementConsignVo.setLogisticsInfo(cOrderEntity.getLogisticsInfo());
                orderManagementConsignVo.setLogisticsState(cOrderEntity.getLogisticsState());
                orderManagementConsignVo.setOrderState(cOrderEntity.getOrderState());
                orderManagementConsignVo.setContractState(cOrderEntity.getContractState());

                //根据地区编号查赋予细地址
                String pickAddress = addressService.getAddressByRegionId(consignEntity.getPickupAddress());
                String unloadAddress = addressService.getAddressByRegionId(consignEntity.getUnloadAddress());
                pickAddress += consignEntity.getPickupDetailAddress();
                unloadAddress += consignEntity.getUnloadDetailAddress();
                orderManagementConsignVo.setPickupDetailAddress(pickAddress);
                orderManagementConsignVo.setUnloadDetailAddress(unloadAddress);


                if (unloadCity != null){
                    /**
                     * 删选出地址不符合查询条件的
                     *  返回空的QueryTransportVo
                     */
                    AddressEntity endCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", consignEntity.getUnloadAddress()));
                    if(!endCity.getAddressRegionid().equals(unloadCity)){
                        //地址条件不符
                        return new OrderManagementConsignVo();
                    }else {
                        return orderManagementConsignVo;
                    }
                }

            }
            return orderManagementConsignVo;
        }).collect(Collectors.toList());

        //用迭代器删除值为空的元素（迭代器遍历不会报错 foreach会）
        Iterator iterator = orderManagementConsignVoList.iterator();
        while (iterator.hasNext()){
            OrderManagementConsignVo vo = (OrderManagementConsignVo) iterator.next();
            if(vo.getId() == null){
                iterator.remove();
            }

        }

        IPage<COrderEntity> page = this.page(
                new Query<COrderEntity>().getPage(params),
                new QueryWrapper<COrderEntity>()
        );
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(orderManagementConsignVoList);
        System.out.println("ppppppppppppppppppppppp:" + orderManagementConsignVoList);
        return pageUtils;
    }

    @Override
    public R updateOrderStateById(String id) {
        COrderEntity cOrderEntity = this.baseMapper.selectById(id);
        if (cOrderEntity != null) {
            if (cOrderEntity.getOrderState() == 1){
                return R.ok().put("data","已确定收货,无需重复收获");
            }else {
                int result = cOrderDao.updateOrderStateById(id);
                if (result >= 1){
                    return R.ok().put("data","确定收货成功");
                }else {
                    return R.ok().put("data","系统繁忙,收货失败,请稍后重试");
                }
            }


        }else {
            return R.ok().put("data","系统繁忙,稍后重试");
        }
    }

}




